<?php

/**
 * 命令行执行，http 服务
 * @noinspection ForgottenDebugOutputInspection
 */

if (!isset($argv)) return;

require '../comm.php';
include ROOT_PATH . 'app/route/web.php';

use Workerman\Worker;
use Workerman\Lib\Timer;
use Workerman\Autoloader;
use Workerman\Events\EventInterface;
use Workerman\Protocols\Http\Request;
use Workerman\Protocols\Http\Response;
use Workerman\Http\Client as HttpClient;
use Workerman\Redis\Client as RedisClient;

Worker::$logFile = ROOT_PATH.'/runtime/log/http.log';
Worker::$pidFile = ROOT_PATH.'/runtime/pid_http.log';

$httpWorker = new Worker("http://0.0.0.0:8000");

$httpWorker->name = 'MyHttp1';

//启动4个进程 对外提供服务
$httpWorker->count = 4;


$httpWorker->onWorkerStart = function($httpWorker)
{
    echo PHP_EOL. "[onWorkerStart] #$httpWorker->id 进程已启动" .PHP_EOL;

    global $db, $redis, $http; //在此定义数连接

    $http = new HttpClient();
};


$httpWorker->onConnect = function($connection)
{
    echo PHP_EOL. "[onConnect] 新连接 #$connection->id 已上线，IP：" . $connection->getRemoteIp() .PHP_EOL;

    foreach($connection->worker->connections as $conn)
    {
        //echo PHP_EOL. "新连接 #$connection->id 已上线" .PHP_EOL;
    }
};


$httpWorker->onMessage = function($connection, $request)
{
    global $routes;

    $path = ltrim($request->path(), '/');
    if (!$path) {
        echo 'index ok';
        $connection->send(response(200, ["code" => 1, "message"=> "index ok"]));
        return;
    }
    if (!isset($routes[$path])) {
        $connection->send(response(404, ["code" => 404, "message"=> "Not Found"]));
        return;
    }

    $params = $request->get();
    $route = $routes[$path];

    try {
        $data = call_user_func([new $route[0]($request), $route[1]], $params);
        if ($data instanceof Response) {
            $response = $data;
            unset($data);
        }
        else {
            $response = response(200, $data);
        }
    }
    catch (\Throwable $e) {
        $data = json_string(filter_err($e, 1), 1);
        echo PHP_EOL. $data;
        $response = response(500, $data);
    }

    $connection->send($response);
};


$httpWorker->onError = function($connection, $code, $msg)
{
    echo PHP_EOL. "服务异常：($code) $msg." .PHP_EOL;
};


$httpWorker->onClose = function($connection)
{
    echo PHP_EOL. '连接关闭：#' . $connection->id .PHP_EOL;
};


Worker::runAll();


function response ($code, $data, $headers = []) {
    if (is_array($data) || is_object($data)) {
        $data = json_string($data, 1);
        $headers = ['Content-Type' => 'application/json; charset=utf-8'];
    } else {
        $data = (string) $data;
    }
    $headers['Content-Length'] = strlen($data);
    return new Response($code, $headers, $data);
}
